package com.eric.account.service.impl;

import com.eric.account.dao.AccountMapper;
import com.eric.account.entity.Account;
import com.eric.account.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author:Eric
 * @date:2021/7/6
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void insert(Account account) {
        accountMapper.insert(account);
    }

    @Override
    public void update(Account account) {
        accountMapper.updateById(account);
    }

    @Override
    public void delete(Long id) {
        accountMapper.deleteById(id);
    }

    @Override
    public Account getOne(Long id) {
        return accountMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reduce(Account account) {
        Account account1 = accountMapper.selectById(account.getId());
        if (Objects.isNull(account1)) {
            throw new RuntimeException("account not exist");
        }
        BigDecimal nowAmount = account1.getAmount().subtract(account.getAmount());
        if (nowAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("account amount is not enough");
        }
        account1.setAmount(nowAmount);
        accountMapper.updateById(account1);
    }
}
